const io = require('socket.io-client');

import * as express from 'express';
const express_server = express();
express_server.use(express.json());

import { DataServer, DataServerQueue } from './data-server';
import { Config, get_config } from './config';
import { get_task } from './server';
import { TaskQueue } from './task';
import { login } from './login';

const config: Config = get_config();

let data_server_queue = new DataServerQueue();
let task_queue = new TaskQueue();

login(config)
.then(token => {
    const socket = io(config.judger_port_uri, {
        auth: { token: token, }
    });

    // Initial priority
    socket.emit('set-priority', 0);

    // Get task
    socket.on('assign-task', task_id => {
        get_task(config, task_id)
        .then(res => {
            task_queue.push(res);
        })
        .catch(err => {
            console.log(`[Task] get task from server ERR ${err.request.status}`);
        });
    });

    // Data server check-in
    express_server.post('/api/data-server', (req, res) => {
        data_server_queue.push(new DataServer(req.body.ip));
        res.status(200).end();
    });

    express_server.listen(config.port, () => {
        console.log(`Serving on port ${config.port}`);
    });
})
.catch(() => {
    console.log(`[Login] login ERR`);
    process.exit(1);
});
